package net.zjitc.utils.dispacher;

import net.zjitc.utils.ControllerUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/8.
 */
@WebServlet(name = "DispacherServlet",urlPatterns = "/")
public class DispacherServlet extends HttpServlet {
    Map<String,Method> urlMap=new HashMap();
    Map<Method,Object> methodMap=new HashMap();

    @Override
    public void init() throws ServletException {
        String packName="net.zjitc.controller";
        try {
            List<Class> classes= ControllerUtils.getClassAll(packName);
            for (Class c: classes) {
                Method[] methods = c.getMethods();
                for (Method m : methods) {
                    URLMapping annotation=m.getAnnotation(URLMapping.class);
                   if(annotation!=null){
                       String url=annotation.url();
                       urlMap.put(url,m);
                       Object o=c.newInstance();
                       methodMap.put(m,o);

                   }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url=req.getServletPath();
        if(!urlMap.containsKey(url)){
            resp.setStatus(404);
            return;
        }
        Method m=urlMap.get(url);
        Object o=methodMap.get(m);
        try {
            //如果请求是post,则改编码方式为utf-8
            if (req.getMethod().equals("POST")){
                req.setCharacterEncoding("utf-8");
            }
            String str=(String)m.invoke(o,req,resp);
            //如果字符串为空
            if (str==null){
                return;
            }
            //如果不为空
            if(str!=null||(!"".equals(str))){
                if(str.startsWith("Redirect:")){
                    //重定向
                    resp.sendRedirect(str.substring(9));
                }else{
                    //请求转发
                    req.getRequestDispatcher(str).forward(req,resp);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
